package com.wdz.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wdz.annotations.ResponseResult;
import com.wdz.article.entity.Article;
import com.wdz.article_comment.entity.ArticleComment;
import com.wdz.article_comment.service.IArticleCommentService;
import com.wdz.category.entity.Category;
import com.wdz.category.service.ICategoryService;
import com.wdz.http.Response;
import com.wdz.service.IArticleService;
import com.wdz.service.impl.ArticleServiceImpl;
import com.wdz.utils.ApplicationContextUtil;
import com.wdz.utils.RedisFieldName;
import com.wdz.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "文章有关的api接口")
@RestController
public class ArticleController {

    private IArticleService iArticleService;

    private com.wdz.article.service.IArticleService iArticleService2;

    private ICategoryService iCategoryService;

    @Autowired
    public void setIArticleService(IArticleService iArticleService) {
        this.iArticleService = iArticleService;
    }

    @Autowired
    public void setIArticleService2(com.wdz.article.service.IArticleService iArticleService2) {
        this.iArticleService2 = iArticleService2;
    }

    @Autowired
    public void setICategoryService(ICategoryService iCategoryService) {
        this.iCategoryService = iCategoryService;
    }

    @Autowired
    public void setIArticleCommentService(IArticleCommentService iArticleCommentService) {
        this.iArticleCommentService = iArticleCommentService;
    }

    private static final Log log = LogFactory.get();

    /**
     * 分页查询文章列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation("分页查询文章列表")
    @PostMapping("/queryList")
    @SentinelResource(value="queryList")
    public Response queryList(Integer pageNo, Integer pageSize){
        int total = iArticleService2.selectCount(new EntityWrapper<Article>().where("type={0}",0));
        Map<String,Object> data = new HashMap<>();
        data.put("total",total);
        data.put("data",iArticleService.queryListByPage(pageNo,pageSize));
        return Response.success(data);
    }
    /**
     * 分页查询草稿列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/queryDraftList")
    public Response queryDraftList(Integer pageNo, Integer pageSize){
        int total = iArticleService2.selectCount(new EntityWrapper<Article>().where("type={0}",1));
        Map<String,Object> data = new HashMap<>();
        data.put("total",total);
        data.put("data",iArticleService.queryDraftListByPage(pageNo,pageSize));
        return Response.success(data);
    }

    /**
     * 分页查询分类列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/queryCategoryList")
    public Response queryCategoryList(@RequestParam Integer pageNo, @RequestParam Integer pageSize){
        int total = iCategoryService.selectCount(null);
        Map<String,Object> data = new HashMap<>();
        data.put("total",total);
        data.put("data",iArticleService.queryCategoryListByPage(pageNo,pageSize));
        return Response.success(data);
    }
    /**
     * 查询三层分类
     */
    @GetMapping("/queryCategorysByOTM")
    public Response queryCategorysByOTM(){
        return Response.success(iCategoryService.seleteCategorysByOTM());
    }
    /**
     * 添加文章
     */
    @PostMapping("/createArticle")
    public Response createArticle(@RequestBody Article article){
        if(!StringUtils.isEmpty(article.getId())){
            iArticleService2.update(article,new EntityWrapper<Article>().where("id={0}",article.getId()));
        }else {
            iArticleService2.insert(article);
        }
            return Response.success((Object) article.getId());
    }
    /**
     * 删除文章
     */
    @PostMapping("/deleteArticle")
    public Response deleteArticle(@RequestParam String id){
            iArticleService2.deleteById(id);
            return Response.success();
    }

    /**
     * 根据id查询文章数据
     * @param id
     * @return
     */
    @PostMapping("/queryArticle")
    public Response queryArticle(@RequestParam String id){
        ArticleServiceImpl articleService = (ArticleServiceImpl) ApplicationContextUtil.getBean("ArticleServiceImpl2");
        return Response.success(articleService.dgRelationCategoryIds(iArticleService2.selectById(id)));
    }

    /**
     * 查询一级分类列表
     */
    @GetMapping("/queryOneLevelCategory")
    public Response queryOneLevelCategory(){
        return Response.success(iCategoryService.selectList(new EntityWrapper<Category>().where("level={0}",0)));
    }
    /**
     * 根据一级分类id分页查询文章列表
     */
    @PostMapping("/queryArticlesBOLC")
    public Response queryArticlesBOLC(String id,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        if(id == null){
            return queryList(pageNo, pageSize);
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", iArticleService.selectArticleCountBOLC(id));
            data.put("data", iArticleService.queryArticlesBOLC(id, pageNo, pageSize));
            return Response.success(data);
        }
    }
    /**
     * 根据分类id查出关联下的文章列表
     */
    @PostMapping("/queryArticlesByres")
    public Response queryArticlesByres(String id,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        if(id == null){
            return queryList(pageNo, pageSize);
        }else {
            Map<String,Object> data = new HashMap<>();
            data.put("total", iArticleService.queryArticlesByresCount(id));
            data.put("data", iArticleService.queryArticlesByres(id, pageNo, pageSize));
            return Response.success(data);
        }
    }
    /**
     * 模糊搜索文章
     */
    @PostMapping("/likeArticles")
    public Response likeArticles(String name,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Map<String,Object> data = new HashMap<>();
        data.put("total",iArticleService.likeTitleCount(name));
        data.put("data",iArticleService.likeArticles(name, pageNo, pageSize));
        return Response.success(data);
    }
    /**
     * 在一级分类下模糊查询文章
     */
    @PostMapping("/likeArticlesByCate")
    public Response likeArticlesByCate(String name,@RequestParam Integer pageNo,@RequestParam Integer pageSize,String id){
        if(id == null){
            return likeArticles(name, pageNo, pageSize);
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", iArticleService.likeTitleByCateCount(name, id));
            data.put("data", iArticleService.likeArticlesByCate(name, id, pageNo, pageSize));
            return Response.success(data);
        }
    }
    /**
     * 根据访问量进行排序获取到前十篇热门文章
     */
    @GetMapping("/queryHotArticles")
    public Response queryHotArticles(){
        //iArticleService2.selectList(new EntityWrapper<Article>().orderBy("count",false));
        return Response.success(iArticleService2.selectMapsPage(new Page(1,10),new EntityWrapper<Article>().where("type={0}",0).orderBy("count",false)).getRecords());
    }
    /**
     * 根据访问量获取前十篇置顶文章
     */
    @GetMapping("/queryToppingArticles")
    public Response queryToppingArticles(){
        return Response.success(iArticleService2.selectMapsPage(new Page(1,10),new EntityWrapper<Article>().orderBy("count",false).where("is_topping={0} and type={1}",1,0)).getRecords());
    }
    /**
     * 阅读量加 1
     */
    @PostMapping("/plusCount")
    public Response plusCount(@RequestParam String id){
        iArticleService2.updateForSet("count=count+1",new EntityWrapper<Article>().where("id={0}",id));
        return Response.success();
    }
    /**
     * 点赞
     */
    @PostMapping("/plusPraise")
    public Response plusPraise(@RequestParam String id){
        iArticleService2.updateForSet("praise=praise+1",new EntityWrapper<Article>().where("id={0}",id));
        return Response.success();
    }
    @Autowired
    private IArticleCommentService iArticleCommentService;
    /**
     * 发表评论/回复
     */
    @PostMapping("/publishComment")
    public Response publishComment(@RequestBody ArticleComment articleComment){
        iArticleCommentService.insert(articleComment);
        iArticleService2.updateForSet("comments=comments+1",new EntityWrapper<Article>().where("id={0}",articleComment.getArticleId()));
        return Response.success(articleComment);
    }
    /**
     * 根据文章id分页查询评论以及评论下面的回复
     */
    @PostMapping("/queryCommentsAndReplys")
    public Response queryCommentsAndReplys(@RequestParam String id,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Map<String,Object> data = new HashMap<>();
        data.put("total",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("article_id={0} and type={1}",id,0)));
        data.put("data",iArticleService.queryCommentsAndReplys(id, pageNo, pageSize));
        return Response.success(data);
    }

    /**
     * 根据文章id获取评论总数
     */
    @PostMapping("/getCommentsAndReplys")
    public Response getCommentsAndReplys(@RequestParam String id){
        return Response.success(iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("article_id={0}",id)));
   }
    /**
     * 修改文章时将文章id保存进redis，方便后面修改完成后删除之前的草稿
     */
    @PostMapping("/addArticleIdToRedis")
    public Response addArticleIdToRedis(@RequestParam String id){
        RedisUtil redisUtil = RedisUtil.init();
        /*Map<String,Object> map = new HashMap<>();
        map.put(key,id);
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);*/
        //redisUtil.hset("waitForDeleteArticleIds",key,id);
        String uid;
        String rn = RedisFieldName.WAITFORDELETEARTICLEIDS;
        if(redisUtil.hasKey(rn) && !StringUtils.isEmpty((uid=(String)redisUtil.hget(rn,id)))){
            return Response.success((Object)uid);
        }
        Article article = iArticleService2.selectById(id);
        article.setId(null);
        article.setType(1);
        iArticleService2.insert(article);
        uid = article.getId();
        redisUtil.hset(rn,id,uid);
        return Response.success((Object) uid);
    }
    /**
     * 修改文章，并删除之前保存的文章草稿
     */
    @PostMapping("/updateArticle")
    public Response updateArticle(@RequestBody Article article,@RequestParam(value="id") String id){
        iArticleService2.deleteById(article.getId());
        article.setId(id);
        iArticleService2.update(article,new EntityWrapper<Article>().where("id={0}",id));
        RedisUtil redisUtil = RedisUtil.init();
        redisUtil.hdel(RedisFieldName.WAITFORDELETEARTICLEIDS,id);
        return Response.success((Object) id);
    }
    /**
     * 根据点赞数，评论数，阅读数进行排序分页查询
     */
    @GetMapping("/queryTJpage/{pageNo}/{pageSize}")
    public Response queryTJpage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> d = new HashMap<>();
        EntityWrapper<Article> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("type=0");
        d.put("total",iArticleService2.selectCount(entityWrapper));
        entityWrapper.orderBy("is_topping",false);
        entityWrapper.orderBy("praise",false);
        entityWrapper.orderBy("comments",false);
        entityWrapper.orderBy("collections",false);
        entityWrapper.orderBy("count",false);
        d.put("data",iArticleService2.selectPage(new Page<>(pageNo,pageSize),entityWrapper).getRecords());
        return Response.success(d);
    }
    /**
     * 根据id查询上一篇下一篇
     */
    @GetMapping("/queryPreAndNext/{id}")
    @ResponseResult
    public Map<String,Object> queryPreAndNext(@PathVariable String id){return iArticleService2.selectPreAndNextById(id);}

    /**
     * 根据id查询该文章的所属分类下面的5篇文章
     */
    @GetMapping("/queryBrother/{id}")
    @ResponseResult
    public List<Article> queryBrother(@PathVariable String id){
        String parentId = iArticleService2.selectById(id).getParentCategoryId();
        Wrapper<Article> entityWrapper = new EntityWrapper<Article>().where("parent_category_id = {0} and type = 0",id);
        entityWrapper.orderBy("is_topping",false);
        entityWrapper.orderBy("praise",false);
        entityWrapper.orderBy("comments",false);
        entityWrapper.orderBy("collections",false);
        entityWrapper.orderBy("count",false);
        return iArticleService2.selectPage(new Page<>(1,5),entityWrapper).getRecords();
    }

}

